package threads;


import java.awt.*;
import java.awt.event.*;



class MainDisplayTwo {

    int i = 0;
    boolean flag = true;

    void displayAdd() {
        while (true) {
            if (flag) {
                try {
                    wait();
                } catch (Exception e) {
                }
            }
            System.out.println(i++);
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
            }
            notify();
        }
    }

    void displaySub() {
        while (true) {
            if (!flag) {
                try {
                    wait();
                } catch (Exception e) {
                }
            }
            System.out.println(i--);
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
            }
            notify();
        }
    }
    /*
    public static void main(String arg[]) {
        MainDisplayTwo md = new MainDisplayTwo();
        new ShowMeTwo(md);
        new ShowMeTooTwo(md);
        new YouGetUpTwo(md);
    }
     * **/
}
class ShowMeTwo implements Runnable {

    MainDisplayTwo md;
    Thread t;

    ShowMeTwo(MainDisplayTwo md) {
        this.md = md;
        t = new Thread(this);
        t.start();
    }

    public void run() {
        System.out.print("Thread showMe :");
        synchronized (md) {
            md.displayAdd();
        }
    }
}

class ShowMeTooTwo implements Runnable {

    MainDisplayTwo md;
    Thread t;

    ShowMeTooTwo(MainDisplayTwo md) {
        this.md = md;
        t = new Thread(this);
        t.start();
    }

    public void run() {

        System.out.print("Thread showMeToo :");
        synchronized (md) {//Đối tượng trong ngoặc với khối block synchronized là đối tượng đại diện cho lớp có chứa phương thức synchronized
            md.displaySub();
        }
    }
}
class DemoWait2 {
    public static void main(String arg[]) {
        MainDisplayTwo md = new MainDisplayTwo();
        new ShowMeTwo(md);
        new ShowMeTooTwo(md);
        new YouGetUpTwo(md);
    }
}

class YouGetUpTwo extends Frame implements ActionListener {

    Button btn = new Button("Ok");
    MainDisplayTwo md;

    public YouGetUpTwo(MainDisplayTwo md) {
        add(btn);
        this.md = md;
        btn.addActionListener(this);
        setSize(100, 100);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent ae) {
        md.flag = (!(md.flag));
    }
    /*
    public static void main(String arg[]) {
        MainDisplayTwo md = new MainDisplayTwo();
        new ShowMeTwo(md);
        new ShowMeTooTwo(md);
        new youGetUp(md);
    }
     * **/
}
